package com.xl.activiti.demo.task;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.ActivitiException;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.Expression;
import org.activiti.engine.delegate.JavaDelegate;

/**
 * @author zhongwm
 */
@Slf4j
@Setter
public class RestfulService implements JavaDelegate {
    /**
     * 请求URL
     */
    private Expression url;

    /**
     * 请求方式 GET | POST
     */
    private Expression method;

    /**
     * 参数
     */
    private Expression params;

    /**
     * 结果变量
     */
    private Expression resultVariable;


    @Override
    public void execute(DelegateExecution execution) {
        log.info("------------- Start execute ---------------------------");
        log.info("---- execution variable:{}", execution.getVariables());
        String urlValue = (String) url.getValue(execution);
        if (StrUtil.isBlank(urlValue)) {
            log.error("url is blank.");
            throw new ActivitiException("url 不能为空。");
        }

        JSONObject json = new JSONObject();
        if (params != null) {
            Object paramsValue = params.getValue(execution);
            if (paramsValue != null) {
                json = JSONUtil.parseObj(paramsValue.toString());
            }
        }
        String result = null;
        Object methodValue = null;
        if (method != null ) {
            methodValue = method.getValue(execution);
        }
        log.info("Restful url:{}, params:{}, method:{}", urlValue, json, methodValue);
        if (methodValue != null && "post".equalsIgnoreCase((String) methodValue)) {
            result = HttpUtil.post(urlValue, json);
        } else {
            result = HttpUtil.get(urlValue, json);
        }

        if (StrUtil.isBlank(result)) {
            log.error("result is null. url:{}, params:{}", urlValue, json);
            throw new ActivitiException("请求接口失败");
        } else if (resultVariable != null){
            log.info("result:{}, url:{}, params:{}", result, urlValue, json);
            Object variableValue = resultVariable.getValue(execution);
            if (variableValue != null) {
                execution.setVariable(variableValue.toString(), JSONUtil.parseObj(result));
                log.info("set variable name:{}, value:{}", variableValue, result);
            }
        }

    }
}
